package org.adream.account.rest.api;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.adream.account.entity.RoleEntity;
import org.adream.account.model.ResultModel;
import org.adream.account.rest.api.model.BasicSearchForm;
import org.adream.account.rest.api.model.RoleForm;
import org.adream.account.service.ADreamServiceException;
import org.adream.account.service.RoleService;
import org.adream.account.util.Constant;
import org.adream.account.util.FastJson;
import org.adream.account.util.UserUtil;
import org.adream.account.util.Utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.github.pagehelper.PageInfo;

/**
 *	角色 
 */
@RequestMapping("/role/")
@Controller
public class RoleApiController {
	
	private final static Logger logger = LoggerFactory.getLogger(RoleApiController.class);

	@Autowired
	private RoleService roleService;
	
	/**
	 * 新增角色可添加对应的资源
	 * @param form
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "saveRoleRes",produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
	@ResponseBody
	public ResultModel<?> saveRoleRes(@RequestBody RoleForm form, HttpServletRequest request) {
		String uid = UserUtil.getUidByRequest(request);
		if(StringUtils.isEmpty(uid)) {
			logger.warn("登录信息失效");
			return new ResultModel<String>(ResultModel.ERR_PARAM, "登录失效,请重新登录", null);
		}
		//数据有效性判断
		if(form == null || StringUtils.isEmpty(form.getRleName()) || StringUtils.isEmpty(form.getRleName().trim()) || form.getVerify() == null) {
			logger.warn("新增角色失败,参数为空:(");
			return new ResultModel<String>(ResultModel.ERR_PARAM, "新增失败,参数为空", null);
		}
		if(form.getRleName().length() > Constant.COMMON_DATA_LENGTH) {
			logger.warn("新增角色失败,角色名称太长:(");
			return new ResultModel<String>(ResultModel.WARN_DATA_LENGTH, "角色名称太长,请精简", null);
		}
		try {
			return roleService.saveRoleRes(form, request);
		} catch (ADreamServiceException e) {
			logger.warn(e.getMessage());
			return new ResultModel<String>(ResultModel.ERR_DATABASE, e.getMessage(), null);
		}
	}
	
	/**
	 * 删除  逻辑删除 
	 * @param rleId
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "deleteRole", produces = "application/json;charset=UTF-8")
	@ResponseBody
	public ResultModel<?> deleteRole(String rleId,HttpServletRequest request) {
		if (StringUtils.isEmpty(rleId)) {
			return new ResultModel<String>(ResultModel.ERR_PARAM, "请求参数有误", null);
		}
		return roleService.deleteRole(rleId);
	}
	
	/**
	 * 批量删除
	 * @param rleIds
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "deleteRoles",produces = "application/json;charset=UTF-8",method = RequestMethod.POST)
	@ResponseBody
	public ResultModel<?> deleteRoles(@RequestBody String[] rleIds,HttpServletRequest request) {
		if(StringUtils.isEmpty(rleIds)) {
			return new ResultModel<String>(ResultModel.ERR_PARAM, "请求参数有误", null); 
		}
		for (String rleId : rleIds) {
			deleteRole(rleId, request);
		}
		return new ResultModel<String>(ResultModel.SUCCESS, "成功删除Role", null);
	}
	
	/**
	 * 更新角色可更新对应的资源
	 * @param form
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "updateRoleRes",produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
	@ResponseBody
	public ResultModel<?> updateRoleRes(@RequestBody RoleForm form, HttpServletRequest request) {
		String uid = UserUtil.getUidByRequest(request);
		if(StringUtils.isEmpty(uid)) {
			logger.warn("登录信息失效");
			return new ResultModel<String>(ResultModel.ERR_PARAM, "登录失效,请重新登录", null);
		}
		//数据有效性判断
		if(form == null || StringUtils.isEmpty(form.getRleName()) || StringUtils.isEmpty(form.getRleName().trim()) || form.getVerify() == null) {
			logger.warn("新增角色失败,参数为空:(");
			return new ResultModel<String>(ResultModel.ERR_PARAM, "新增失败,参数为空", null);
		}
		if(form.getRleName().length() > Constant.COMMON_DATA_LENGTH) {
			logger.warn("新增角色失败,角色名称太长:(");
			return new ResultModel<String>(ResultModel.WARN_DATA_LENGTH, "角色名称太长,请精简", null);
		}
		try {
			return roleService.updateRoleRes(form, request);
		} catch (ADreamServiceException e) {
			logger.warn(e.getMessage());
			return new ResultModel<String>(ResultModel.ERR_DATABASE, e.getMessage(), null);
		}
	}
	
	/**
	 * 根据删除标志查询role
	 * @param dr
	 * @return
	 */
	@RequestMapping(value = "queryRolesByDr", produces = "application/json;charset=UTF-8")
	@ResponseBody
	public ResultModel<List<RoleEntity>> queryRolesByDr(Integer dr) {
		if (dr == null) {
			return new ResultModel<List<RoleEntity>>(ResultModel.ERR_PARAM, "请求参数有误", null);
		}
		List<RoleEntity> roles = roleService.queryRolesByDr(dr);
		if(Utils.isEmptyCollection(roles)) {
			return new ResultModel<List<RoleEntity>>(ResultModel.NOT_FOUND_OBJECT, "查询失败,数据不存在", null);
		}
		return new ResultModel<List<RoleEntity>>(ResultModel.SUCCESS, "成功获取Role", roles);
	}
	
	/**
	 * 根据是否为认证角色,删除标志查询role
	 * @param dr
	 * @return
	 */
	@RequestMapping(value = "queryRolesByVerifyAndDr", produces = "application/json;charset=UTF-8")
	@ResponseBody
	public ResultModel<List<RoleEntity>> queryRolesByVerifyAndDr(Integer verify,@FastJson("dr") int dr) {
		if (StringUtils.isEmpty(verify) || StringUtils.isEmpty(String.valueOf(dr))) {
			return new ResultModel<List<RoleEntity>>(ResultModel.ERR_PARAM, "请求参数有误", null);
		}
		List<RoleEntity> roles = roleService.queryRolesByVerifyAndDr(verify, dr);
		if(Utils.isEmptyCollection(roles)) {
			return new ResultModel<List<RoleEntity>>(ResultModel.NOT_FOUND_OBJECT, "查询失败,数据不存在", null);
		}
		return new ResultModel<List<RoleEntity>>(ResultModel.SUCCESS, "成功获取Role", roles);
	}

	/**
	 * 根据role id查询role
	 * @param rleId role id
	 * @return
	 */
	@RequestMapping(value = "queryRoleByRleId", produces = "application/json;charset=UTF-8")
	@ResponseBody
	public ResultModel<RoleEntity> queryRoleByRleId(String rleId) {
		if (StringUtils.isEmpty(rleId)) {
			return new ResultModel<RoleEntity>(ResultModel.ERR_PARAM, "请求参数有误", null);
		}
		RoleEntity role = roleService.queryRoleByRleId(rleId);
		if(role == null) {
			return new ResultModel<RoleEntity>(ResultModel.NOT_FOUND_OBJECT, "查询失败,数据不存在", null);
		}
		return new ResultModel<RoleEntity>(ResultModel.SUCCESS, "成功获取Role", role);
	}
	
	/**
	 * 检查role name是否存在
	 * @param rleName role name
	 * @param response
	 */
	@RequestMapping(value = "checkRleName")
	public void checkRleName(String rleName,HttpServletResponse response) {
		boolean result = roleService.isValidRleName(rleName);
		PrintWriter out = null;
		try {
			out = response.getWriter();
			out.write(String.valueOf(result));
		} catch (IOException e) {
			logger.warn("检查role name出错:)");
		} finally {
			if(out != null) {
				out.close();
			}
		}
	}
	
	/**
	 * 分页查询
	 * @param form	请求表单
	 * @return
	 */
	@RequestMapping(value = "/selectPageRoles", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
	@ResponseBody
	public ResultModel<?> selectPageRoles(@RequestBody BasicSearchForm form) {
		if(form == null || StringUtils.isEmpty(form.getDr())) {
			return new ResultModel<String>(ResultModel.ERR_PARAM, "查询失败,请求参数有误", null);
		}
		PageInfo<RoleEntity> page = roleService.selectPageRoles(form.getDr(), form.getPageNo(), form.getPageSize());
		return new ResultModel<PageInfo<RoleEntity>>(ResultModel.SUCCESS, "查询成功", page);
	}
}